#include "blockFreeList.h"
#include "disk.h"
#include "directory.h"
#include <limits.h>

#define NO_FREE_BLOCKS -1
#define SUPER_BLOCK_NUMBER 0
#define START_OF_BLOCKS 16
#define START_OF_INODES 3
int initFreeList(){
	int disknum = openDisk("root", DISK_SIZE);
	int* list = malloc(sizeof(int)*(BLOCKS));
	int errnum = readBlock(disknum, SUPER_BLOCK_NUMBER, list);
	memcpy(freelist.bitmap, list,sizeof(int)*(BLOCKS));
	freelist.numberofelements = DISK_SIZE/(sizeof(int) * BITS_PER_BYTE);

}

int getUnusedBlockNumber(){
	int i;
	for(i = START_OF_BLOCKS; i < freelist.numberofelements; i++){
		//if int is all ones then there's no free blocks left
		if(freelist.bitmap[i] == INT_MAX) continue;
		int j;
		int bitmap = freelist.bitmap[i];
		for(j = 0; j < 8; j++){
			//if bit is a zero then block is free
			if(!(bitmap & 1)){
				return i*32+j;
			}else bitmap >>=1;
		}

	}
	return NO_FREE_BLOCKS;



}

int getUnusedInodeNumber(){
	int i;
	for(i = START_OF_INODES; i < START_OF_BLOCKS-1; i++){
		//if int is all ones then there's no free blocks left
		if(freelist.bitmap[i] == INT_MAX) break;
		int j;
		for(j = 0; j < 8; j++){
			//if bit is a zero then block is free
			if(!(freelist.bitmap[i] & 1)){
				return i*32+j;
			}
		}

	}
	return NO_FREE_BLOCKS;




}

void setBlockToUsed(int blockNumber){
  int numtimesdivisedby = 0;

  while(blockNumber >=32){
	  blockNumber/=32;
	  numtimesdivisedby++;
  }
  int usedBlock = 1;
  //now usedBlock contains the bit to set
  usedBlock <<= blockNumber;
  freelist.bitmap[numtimesdivisedby] = freelist.bitmap[numtimesdivisedby] | usedBlock;

}
void setBlockToUnused(int blockNumber){
  int numtimesdivisedby = 0;

  while(blockNumber >=32){
	  blockNumber/=32;
	  numtimesdivisedby++;
  }
  int unusedBlock = 0;
  //now usedBlock contains the bit to set
  unusedBlock <<= blockNumber;
  freelist.bitmap[numtimesdivisedby] = freelist.bitmap[numtimesdivisedby] & unusedBlock;
}
